package com.gagakuai.bpm.service.camunda.impl;

import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.gagakuai.bpm.domian.dto.camunda.WorkflowDeploymentDto;
import com.gagakuai.bpm.domian.dto.request.PageRequest;
import com.gagakuai.bpm.domian.dto.response.PageData;
import com.gagakuai.bpm.service.camunda.WorkflowDeploymentService;

import com.gagakuai.bpm.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.repository.DeploymentQuery;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/*
 * bpm
 */
@Service
@Slf4j
public class WorkflowDeploymentServiceImpl implements WorkflowDeploymentService {

    @Resource
    private RepositoryService repositoryService;

    @Override
    public void bpmnModelDeployFile(MultipartFile file, String name) {
        if(file == null){
            throw new ApiException("流程文件不能为空！");
        }

        //Long tenantId = new Random().nextLong();
        try {
            repositoryService.createDeployment()
                    //.tenantId(String.valueOf(tenantId))
                    .name(name) // 流程名字
                    .source("公司的流程") // 来源
                    .addInputStream(file.getOriginalFilename(), file.getInputStream())
                    .deploy();

        } catch (Exception e) {
            throw new ApiException("流程部署失败".concat(e.getMessage()));
        }
    }

    @Override
    public void redeployResource(WorkflowDeploymentDto dto) {
        if(StringUtils.isBlank(dto.getId()) || StringUtils.isBlank(dto.getTenantId())){
            throw new ApiException("参数Id不能为空");
        }

        repositoryService.createDeployment()
                         .tenantId(dto.getTenantId())
                         .nameFromDeployment(dto.getId())
                         .addDeploymentResources(dto.getId())
                         .deploy();
    }

    @Override
    public PageData<WorkflowDeploymentDto> listDeploymentByPage(PageRequest<WorkflowDeploymentDto> pageRequest) {

        WorkflowDeploymentDto condition = pageRequest.getCondition();
        DeploymentQuery deploymentQuery = repositoryService.createDeploymentQuery();

        if( condition != null && StringUtils.isNotBlank(condition.getTenantId())){
            deploymentQuery.tenantIdIn(String.valueOf(condition.getTenantId()));
        }

        // 根据部署名称查询
        if (condition != null && StringUtils.isNotBlank(condition.getName())) {
            deploymentQuery.deploymentNameLike("%".concat(condition.getName()).concat("%"));
        }

        long total = deploymentQuery.count();
        List<Deployment> deployments = deploymentQuery.orderByDeploymentTime().desc().listPage(pageRequest.getStart(0), pageRequest.getRows());

        List<WorkflowDeploymentDto> deploymentList = new ArrayList<>();
        deployments.forEach(d -> {
            WorkflowDeploymentDto dto = new WorkflowDeploymentDto();
            dto.setId(d.getId())
                    .setName(d.getName())
                    .setDeploymentTime(d.getDeploymentTime())
                    .setSource(d.getSource())
                    .setTenantId(d.getTenantId());
            deploymentList.add(dto);
        });

        PageData<WorkflowDeploymentDto> pageData = new PageData<>(pageRequest);
        pageData.setTotal(total).calcPages().setContent(deploymentList);
        return pageData;
    }

    @Override
    public void deleteDeploymet(String id) {
        repositoryService.deleteDeployment(id, true);
    }
}
